package org.ruoyi.aibox.service.impl;

import cn.hutool.core.io.FileUtil;
import org.ruoyi.common.core.utils.MapstructUtils;
import org.ruoyi.core.page.TableDataInfo;
import org.ruoyi.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ruoyi.aibox.domain.bo.AuditTaskBo;
import org.ruoyi.aibox.domain.vo.AuditTaskVo;
import org.ruoyi.aibox.domain.AuditTask;
import org.ruoyi.aibox.domain.DocAuditResult;
import org.ruoyi.aibox.domain.DocAuditResultDetail;
import org.ruoyi.aibox.mapper.AuditTaskMapper;
import org.ruoyi.aibox.mapper.DocAuditResultMapper;
import org.ruoyi.aibox.mapper.DocAuditResultDetailMapper;
import org.ruoyi.aibox.service.IAuditTaskService;
import org.ruoyi.common.core.exception.ServiceException;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.core.utils.file.FileUtils;
import org.ruoyi.common.satoken.utils.LoginHelper;
import org.ruoyi.system.domain.SysFileInfo;
import org.ruoyi.system.service.ISysFileInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 审核任务Service业务层处理
 *
 * @author xpeter
 * @date 2025-04-24
 */
@RequiredArgsConstructor
@Service
public class AuditTaskServiceImpl implements IAuditTaskService {

    private final AuditTaskMapper baseMapper;
    private final DocAuditResultMapper resultMapper;
    private final DocAuditResultDetailMapper resultDetailMapper;
    private final ISysFileInfoService sysFileInfoService;

    @Value("${ruoyi.file.upload-path:D:/ruoyi/uploadPath}")
    private String uploadPath;

    private static final String[] ALLOWED_EXTENSIONS = {"docx"};

    /**
     * 查询审核任务
     */
    @Override
    public AuditTaskVo queryById(Long taskId){
        return baseMapper.selectVoById(taskId);
    }

    /**
     * 查询审核任务列表
     */
    @Override
    public TableDataInfo<AuditTaskVo> queryPageList(AuditTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AuditTask> lqw = buildQueryWrapper(bo);
        Page<AuditTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询审核任务列表
     */
    @Override
    public List<AuditTaskVo> queryList(AuditTaskBo bo) {
        LambdaQueryWrapper<AuditTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AuditTask> buildQueryWrapper(AuditTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AuditTask> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getAuditObjectName()), AuditTask::getAuditObjectName, bo.getAuditObjectName());
        lqw.like(bo.getTotalItems() != null, AuditTask::getTotalItems, bo.getTotalItems());
        lqw.like(bo.getAuditedItems() != null, AuditTask::getAuditedItems, bo.getAuditedItems());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskStatus()), AuditTask::getTaskStatus, bo.getTaskStatus());
        lqw.eq(bo.getStartTime() != null, AuditTask::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, AuditTask::getEndTime, bo.getEndTime());
        return lqw;
    }

    /**
     * 新增审核任务
     */
    @Override
    public Boolean insertByBo(AuditTaskBo bo) {
        AuditTask add = MapstructUtils.convert(bo, AuditTask.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTaskId(add.getTaskId());
        }
        return flag;
    }

    /**
     * 修改审核任务
     */
    @Override
    public Boolean updateByBo(AuditTaskBo bo) {
        AuditTask update = MapstructUtils.convert(bo, AuditTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AuditTask entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除审核任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 提交AI审核任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String submitTask(MultipartFile file, String modelName, String[] auditItemIds) {
        try {
            // 1. 上传文件
            SysFileInfo fileInfo = sysFileInfoService.upload(file, "audit");

            // 2. 创建审核任务
            AuditTask task = new AuditTask();
            task.setCreateBy(LoginHelper.getUserId());
            task.setCreateTime(new Date());
            task.setTaskStatus("0"); // 待审核状态
            task.setAuditObjectName(fileInfo.getOriginalFilename()); // 设置审核对象名称为原始文件名
            // task.setDocId(fileInfo.getId()); // 设置文档ID
            // task.setDocName(fileInfo.getOriginalFilename()); // 设置文档名称
            // task.setDocType(fileInfo.getExt()); // 设置文档类型
            // task.setModelName(modelName); // 设置模型名称
            baseMapper.insert(task);

            // 3. 创建审核结果记录
            DocAuditResult result = new DocAuditResult();
            result.setTaskId(task.getTaskId());
            result.setDocId(fileInfo.getId());
            result.setDocName(fileInfo.getOriginalFilename());
            result.setDocType(fileInfo.getExt());
            result.setAuditObjectName(task.getAuditObjectName());
            result.setModelName(modelName);
            result.setAuditStatus("0"); // 待审核状态
            result.setTotalItems(0L); // 初始化为0，后续更新
            result.setAuditPassItems(0L); // 初始化为0，后续更新
            result.setAuditedItems(0L); // 初始化为0，后续更新
            result.setAuditScore(0L); // 初始化为0，后续更新
            result.setAuditAiConclusion(""); // 初始化为空，后续更新
            result.setCreateBy(LoginHelper.getUserId());
            result.setCreateTime(new Date());
            resultMapper.insert(result);

            // 4. 创建审核结果详情记录
            List<DocAuditResultDetail> details = new ArrayList<>();
            for (String auditItemId : auditItemIds) {
                DocAuditResultDetail detail = new DocAuditResultDetail();
                detail.setResultId(result.getResultId());
                detail.setAuditItemId(Long.valueOf(auditItemId));
                detail.setCreateBy(LoginHelper.getUserId());
                detail.setCreateTime(new Date());
                details.add(detail);
            }
            resultDetailMapper.insertBatch(details);

            return task.getTaskId().toString();
        } catch (Exception e) {
            throw new ServiceException("提交审核任务失败: " + e.getMessage());
        }
    }
}
